<template>
    <div class="print-designer">
        <el-scrollbar>
            <div class="page-size" :style="{ width: '100%' }">
                <div class="num2">纸张大小(mm)
                    <el-input-number @change="updatePageNumberEv" size="small" v-model="page.width" :min="1" :max="1000"
                        label="描述文字"></el-input-number>
                    <el-input-number @change="updatePageNumberEv" size="small" v-model="page.height" :min="1"
                        :max="1000" label="描述文字"></el-input-number>
                    <el-button @click="addTemplateEv" size="small">新增</el-button>
                    <el-button @click="addPageEv" size="small">保存</el-button>
                    <el-button @click="getTemplateEv" size="small">模板</el-button>
                    <el-button @click="previewPrintViewEv" size="small">预览</el-button>
                </div>
            </div>
            <div class="drop-content" ref="dropcontent">
                <div class="designer-left">
                    <div class="draggable-item" draggable="true" @dragstart="handleDragStart('label')">
                        标签
                    </div>
                    <div class="draggable-item" draggable="true" @dragstart="handleDragStart('text')">
                        文本框
                    </div>
                    <div class="draggable-item" draggable="true" @dragstart="handleDragStart('code')">
                        二维码
                    </div>
                    <div class="draggable-item" draggable="true" @dragstart="handleDragStart('images')">
                        图像
                    </div>
                    <div class="draggable-item" draggable="true" @dragstart="handleDragStart('line1')">
                        横线
                    </div>
                    <div class="draggable-item" draggable="true" @dragstart="handleDragStart('line2')">
                        竖线
                    </div>
                </div>
                <div class="designer-right">
                    <div class="top">
                        <cs-ruler :isCrosswise="false" :elementWidth="elementWidth" class="rules-msg"></cs-ruler>
                    </div>
                    <div class="pailie">
                        <div class="left">
                            <cs-ruler :isCrosswise="true" :elementWidth="elementHeight" class="rules-msg"></cs-ruler>
                        </div>
                        <div class="right" :style="{ width: elementWidth + 'mm' }">
                            <div class="drop-target"
                                :style="{ width: designer.width + 'mm', height: designer.height + 'mm' }"
                                ref="droptargetref" @dragover.prevent @drop="handleDrop">
                                <vue-drag-resize @dragstop="onDragstop" :parentLimitation="true" :isResizable="false"
                                    :class="index == activeIndex ? 'vue-drag-resize vue-drag-resize-active' : 'vue-drag-resize'"
                                    :w="'auto'" :h="'auto'" :minh="10" :minw="10"
                                    v-for="(droppedItem, index) in designer.template" :x="droppedItem.w_x"
                                    :y="droppedItem.w_y" :key="droppedItem.id">

                                    <!-- :style="{width: '100%',height:'100%',fontSize:droppedItem.fontSize + 'mm',borderBottom:droppedItem.isLine==true? droppedItem.lineineWidth  + 'mm solid' + droppedItem.lineColorHtml:''}"> -->
                                    <div @click="updateRow(index)" v-on:dblclick="delEv(index)" class="dropped-item"
                                        :id="'filed' + droppedItem.id" :ref="'filed' + droppedItem.id"
                                        :style="droppedItemStyle(droppedItem)">
                                        <div v-if="droppedItem.w_type == 'images'"><img width="100%" height="100%"
                                                src='/static/images/codeImage.png' alt='' title='' /></div>
                                        <div v-else-if="droppedItem.w_type == 'code'"><img width="100%" height="100%"
                                                src='/static/images/code.png' alt='' title='' /></div>
                                        <span v-else="droppedItem.w_type=='code'">{{ droppedItem.text }}</span>
                                    </div>
                                </vue-drag-resize>
                            </div>
                        </div>
                        <div class="designer-filed">
                            <field-cinfig ref="fieldcinfigref" @propsDataEv="propsDataEv"></field-cinfig>
                        </div>

                    </div>
                </div>
            </div>
            <div class="designer-template">
                <div><el-button @click="getDesignerStr" size="small">获取打印模板</el-button></div>
                <div :style="{ width: page.width + 'mm' }">
                    <!-- <pre>{{ designer }}</pre> -->
                    <el-input size="small" type="textarea" :rows="6" placeholder="请输入内容" v-model="designerStr">
                    </el-input>
                </div>
            </div>
        </el-scrollbar>
        <el-dialog class="dialog-def" :fullscreen="fullscreen" v-model="dialogVisibleShow" width="100%">
            <template #header>
                <div class="dialog-title">
                    <div class="left">
                        预览
                    </div>
                    <div class="right">
                        <el-icon style="cursor:pointer;" @click="fullscreen = !fullscreen">
                            <CopyDocument v-if="fullscreen == true" />
                            <FullScreen v-else />
                        </el-icon>
                    </div>
                </div>
            </template>
            <div style="height: 100%; display: flex; align-items: center;justify-content: center;">
                <iframe width="100%" height="100%" :src="previewDataStr"></iframe>
            </div>
        </el-dialog>
        <add ref="refadd" @emitGetDataEv="emitGetDataEv" :printOrderList="printOrderList" />
        <listc ref="reflist" :printOrderList="printOrderList" @emitListEditEv="emitListEditEv" />
    </div>
</template>

<script setup>
import {
    FullScreen,
    CopyDocument
} from '@element-plus/icons-vue'
import VueDragResize from "vue-drag-resize/src";
import csRuler from '@/views/setting/codeDesigner/components/ruler.vue'
import fieldCinfig from '@/views/setting/codeDesigner/components/field.vue'
import add from '@/views/setting/codeDesigner/components/add.vue'
import listc from '@/views/setting/codeDesigner/components/list.vue'
import { ref, reactive, onMounted, onActivated } from 'vue'
import { BasicPrintPreviewListPost } from '@/api/index1Api/print/index.js'
import { PrintOrderListGet } from '@/api/setting/printCode/index.js'
import { loadingStore } from '@/stores/index.js'
const designerStr = ref("")
const page = reactive({
    width: 100,
    height: 80,
})
const loading = loadingStore()
const isAdd = ref(true)
const editId = ref(null)
const fullscreen = ref(false)
const printOrderList = ref([])
const refadd = ref(null)
const reflist = ref(null)
const previewDataStr = ref("")
const dialogVisibleShow = ref(false)
const topWidth = ref(100)
const elementWidth = ref(120)
const elementHeight = ref(100)
const designer = reactive({
    width: 100,
    height: 80,
    template: [
    ]
})
const activeIndex = ref(-1)
const templateItmType = ref("")
const dragData = ref(Date.now())
const letf = ref(0)
const top = ref(0)
const editLeft = ref(0)
const editTop = ref(0)
const droptargetref = ref()
const fieldcinfigref = ref()
onMounted(() => {
    printOrderGetEv()
});
onActivated(() => {

})

// 修改纸张大小
const updatePageEv = () => {
    elementWidth.value = page.width + page.width % 10
    elementHeight.value = page.height + page.height % 10

    // 当尺寸纸张尺寸过小时候调整尺寸长框
    if (elementWidth.value < 120) {
        elementWidth.value = 120
    }
    if (elementHeight.value < 100) {
        elementHeight.value = 100
    }
    designer.width = page.width
    designer.height = page.height
}

// 开始拖拽元素
const handleDragStart = (type_z) => {
    // 设置拖拽数据，通常是元素的ID或数据  
    console.log('开始拖拽')
    // 获取纸张相对左边跟底部的距离（px）
    let droptargetElement = droptargetref.value.getBoundingClientRect()
    letf.value = droptargetElement.left
    top.value = droptargetElement.top
    templateItmType.value = type_z
    dragData.value = Date.now();
}
const handleDrop = (event) => {
    console.log('拖拽结束')

    // 获取拖拽数据  
    const itemId = dragData.value;
    let type_z = templateItmType.value
    let text_z = '文本'
    let isLine_z = 0
    let height_z = 4
    let width_z = 40
    let overflowLessen_z = 0
    if (templateItmType.value == 'line1') {
        text_z = '横线'
        isLine_z = 1
        type_z = 'line'
        height_z = 4
        width_z = 40
    } else if (templateItmType.value == 'line2') {
        text_z = '竖线'
        isLine_z = 1
        type_z = 'line'
        height_z = 40
        width_z = 2
    } else if (templateItmType.value == 'text') {
        text_z = '文本框'
        height_z = 4
        width_z = 40
        isLine_z = 1
        overflowLessen_z = 1
    } else if (templateItmType.value == 'label') {
        text_z = '标签'
        height_z = 4
        width_z = 40
        overflowLessen_z = 1
    } else if (templateItmType.value == 'code') {
        text_z = '条码'
        height_z = 20
        width_z = 20
    } else if (templateItmType.value == 'images') {
        text_z = '图片'
        height_z = 20
        width_z = 20
    } else {
        ElMessage.error('元素异常')
        return
    }

    // console.log(width_z, height_z)


    let darpData = {
        id: itemId,
        // 元素相对设计器的x坐标
        w_x: event.clientX - letf.value,
        // 元素相对设计器的y坐标
        w_y: event.clientY - top.value,
        // w_w: 120,
        // w_h: 20,
        w_type: templateItmType.value,
        field: '',  //字段
        x: 0, //x坐标
        y: 0, //y坐标
        x1: 0, //x1坐标
        y1: 0, //y1坐标
        align: 'left', //对齐方式left左，center居中，right右
        type: type_z,//类型text文本框、line、线条、code条码、images图片、label标签
        path: '',//图片名称非地址
        text: text_z, //字符文本
        width: width_z,//宽度（图片、条码时候的框）
        height: height_z,//高度（图片、条码时候的高）
        fontName: 'simhei', //字体名称
        fontSize: 4, //字体大小
        textWidth: width_z, //文本宽的长度
        fontColor: '#000000', //字体颜色
        overflow: 1, //超出处理1，直接阶段2，省略号隐藏3自动换行，其他参数不处理
        overflowLessen: overflowLessen_z, //超出自动缩小
        isLine: isLine_z, //是否增加横线
        lineTop: 0, //横线距离
        lineineWidth: 0.1, //横线宽度
        lineColorHtml: '#000000', //横线颜色
        rowNumber: 999 //超出显示行数
    }
    // 添加元素
    // 将拖拽的项添加到已放置的项数组中  
    designer.template.push(darpData);
    console.log(darpData)

    // 调整配置选项
    let fieldcinfig = fieldcinfigref.value
    activeIndex.value = designer.template.length - 1
    fieldcinfig.index = designer.template.length - 1
    fieldcinfig.data = JSON.parse(JSON.stringify(darpData))
    // console.log(event)
}
// 序列化打印模板
const designerSerialize = () => {
    if (designer.template.length == 0) {
        ElMessage.error('没有打印元素')
        return
    }
    // 获取像素与mm的比例
    let designerWidthPx = droptargetref.value.clientWidth
    let scalePxMm = designerWidthPx / designer.width
    const parentElement = droptargetref.value.getBoundingClientRect()
    designer.template.forEach(element => {
        // console.log(element)
        // let elementPo = this.$refs['filed' + element.id][0].getBoundingClientRect()
        let elementPo = document.getElementById('filed' + element.id).getBoundingClientRect()
        // console.log(elementPo)
        const relativeLeft = elementPo.left - parentElement.left
        // const relativeTop = elementPo.top - parentElement.top
        const relativeBottom = parentElement.bottom - elementPo.bottom
        element.x = relativeLeft / scalePxMm
        element.y = relativeBottom / scalePxMm

        if (element.w_type == 'line1') {
            element.x1 = relativeLeft / scalePxMm + element.textWidth
            element.y1 = relativeBottom / scalePxMm
        }
        if (element.w_type == 'line2') {
            // console.log('line2', element.textWidth)
            element.x1 = relativeLeft / scalePxMm
            element.y1 = relativeBottom / scalePxMm + element.height
        }
    })
}
// 点击保存方法
const addPageEv = async () => {
    // console.log('点击保存')
    if (designer.template.length == 0) {
        ElMessage.error('没有打印元素')
        return
    }
    await designerSerialize()
    refadd.value.dialogVisible = true
    console.log(isAdd.value)
    console.log(editId.value)
    refadd.value.isAdd = isAdd.value
    refadd.value.editData.template = JSON.parse(JSON.stringify(designer))
    refadd.value.editId = editId.value
}

// 保存成功的回调
const emitGetDataEv = (name, print_order_code) => {
    console.log('aaaaa')
    console.log('aaaaa', name, print_order_code)
    reflist.value.dialogVisible = true
    reflist.value.tableObjData.name = name
    reflist.value.tableObjData.print_order_code = print_order_code
    reflist.value.getEv()
}
// list中点击编辑回调
const emitListEditEv = (data, rowId) => {
    isAdd.value = false
    page.width = data.template.width
    page.height = data.template.height
    let templateData = JSON.parse(JSON.stringify(data.template))

    Object.assign(designer, templateData)
    editId.value = rowId
    refadd.value.editData.name = data.name
    refadd.value.editData.print_order_code = data.print_order_code
}

// 查询打印模板
const getTemplateEv = () => {
    reflist.value.dialogVisible = true
    reflist.value.getEv(false)
}

// 获取打印模板字符
const getDesignerStr = () => {
    designerSerialize()
    designerStr.value = JSON.stringify(designer, null, 2)
}
// 接收模板项数据
const propsDataEv = (index, data) => {
    // 接收配置组件修改后的元素参数信息
    console.log('子组件调用修改提交是乬')
    let dataStr = JSON.parse(JSON.stringify(designer))
    console.log(JSON.parse(JSON.stringify(data)))
    dataStr.template[index] = JSON.parse(JSON.stringify(data))
    dataStr.template[index].id = Date.now()
    dataStr.template[index].w_x = editLeft.value
    dataStr.template[index].w_y = editTop.value
    designer.template = [...dataStr.template]
    // console.log(data)
}

// 删除元素
const delEv = async (index) => {
    console.log('点击删除')
    const message = await ElMessageBox.confirm('确定移除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning ',
        confirmButtonClass: 'confirm-suer',
        cancelButtonClass: 'confirm-cancel',
        roundButton: true,
    }).catch((err) => err)

    if (message === 'confirm') {
        designer.template.splice(index, 1)
        let fieldcinfig = fieldcinfigref.value
        fieldcinfig.index = -1
        fieldcinfig.data = {}
        activeIndex.value = -1
    }
}

// 点击修改元素
const updateRow = (index) => {
    console.log('点击修改元素')

    let fieldcinfig = fieldcinfigref.value
    console.log(fieldcinfig)
    fieldcinfig.index = index
    activeIndex.value = index
    fieldcinfig.data = JSON.parse(JSON.stringify(designer.template[index]))
}
const droppedItemStyle = (itm) => {
    // 动态设计设计器css样式
    // <!-- :style="{width: '100%',height:'100%',fontSize:droppedItem.fontSize + 'mm',borderBottom:droppedItem.isLine==true? droppedItem.lineineWidth  + 'mm solid' + droppedItem.lineColorHtml:''}"> -->
    let styleData = {}
    styleData.width = itm.width + 'mm'
    styleData.height = itm.height + 'mm'
    styleData.fontSize = itm.fontSize - 1 + 'mm'
    styleData.fontFamily = itm.fontName
    styleData.textAlign = itm.align
    styleData.color = itm.fontColor

    if (itm.isLine == true) {
        if (itm.w_type == 'line2') {
            styleData.borderLeft = itm.lineineWidth + 'mm solid' + itm.lineColorHtml
        } else if (itm.w_type == 'code') {
            styleData.border = '0.1mm solid #000000'
        } else if (itm.w_type == 'images') {
            styleData.border = '0.1mm solid #000000'
        }
        else {
            styleData.borderBottom = itm.lineineWidth + 'mm solid' + itm.lineColorHtml
        }
    }
    // console.log(111)
    // console.log(itm.w_type)

    if (itm.w_type == 'text') {
        styleData.width = itm.textWidth + 'mm'
        styleData.height = itm.fontSize + 'mm'
    }

    if (itm.w_type == 'label') {
        styleData.width = itm.textWidth + 'mm'
        styleData.height = itm.fontSize + 'mm'
    }

    if (itm.w_type == 'line1') {
        styleData.width = itm.textWidth + 'mm'
    }

    if (itm.w_type == 'line2') {
        styleData.width = itm.textWidth + 'mm'
    }

    if (itm.w_type == 'code') {
        styleData.border = '0.1mm solid #000000'
    }

    if (itm.w_type == 'images') {
        styleData.border = '0.1mm solid #000000'
    }

    return styleData
}
const previewPrintViewEv = async () => {
    if (designer.template.length == 0) {
        ElMessage.error('没有打印元素')
        return
    }
    await designerSerialize()
    loading.loading = true
    // let printData = [{}]
    // designer.template.forEach(element => {
    //     if (element.field != '') {
    //         printData[0][element.field] = element.text
    //     }
    // })
    try {
        // console.log('designer',designer)
        // console.log('printData',printData)
        let arr_data = await BasicPrintPreviewListPost({ printTemplate: designer })
        if (arr_data.status != 200) {
            return
        }
        console.log(arr_data)
        ElMessage.success('预览成功')

        dialogVisibleShow.value = true
        // dialogVisibleShow.value = true
        previewDataStr.value = arr_data.data.result
        console.log(previewDataStr.value)

        // this.previewDataStr = pywebviewData.data
    } catch (error) {
        ElMessage.error('预览失败' + error)
    } finally {
        loading.loading = false
    }

}
// 获取打印单据
const printOrderGetEv = async () => {
    let arr_data = await PrintOrderListGet({})
    if (arr_data.status != 200) {
        return
    }
    printOrderList.value = arr_data.data.result.data
}

const onDragstop = (element) => {
    console.log('调整拖拽结束', element)

    editLeft.value = element.left
    editTop.value = element.top
}

const updatePageNumberEv = () => {
    updatePageEv()
}

const addTemplateEv = () => {
    console.log('新增打印模板')
    page.width = 100
    page.height = 80
    designer.width = 100
    designer.height = 80
    designer.template = []
    isAdd.value = true
    editId.value = null
}


</script>

<style lang='less' scoped>
@font-face {
    font-family: 'simheiBold';
    src: url('/static/fonts/simhei-bold.ttf') format('woff2');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: 'simhei';
    src: url('/static/fonts/simhei.ttf') format('woff2');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: 'SimSunBold';
    src: url('/static/fonts/SimSun-bold.ttf') format('woff2');
    font-weight: normal;
    font-style: normal;
}

@font-face {
    font-family: 'SimSun';
    src: url('/static/fonts/SimSun.ttf') format('woff2');
    font-weight: normal;
    font-style: normal;
}

.draggable-item {
    width: 100px;
    height: 30px;
    line-height: 30px;
    /* background-color: #E3E3E3; */
    border: 1px solid #8E8E8E;
    color: #8E8E8E;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: move;
    margin-bottom: 10px;
}

.drop-target {
    border: 1px dotted black;
    position: relative;
}


/* ===================== */
.print-designer {
    /* padding: 30px; */
    /* box-sizing: border-box; */
    height: 100%;
    display: flex;
    flex-direction: column;
    /* justify-content: center; */
    /* align-items: center; */
    /* background-color: pink; */

}

.page-size {
    padding-bottom: 5px;
    padding-left: 10px;
    box-sizing: border-box;

    .num1,
    .num2 {
        height: 35px;
        line-height: 35px;
    }
}

.drop-content {
    padding-left: 10px;
    box-sizing: border-box;
    display: flex;
}

.designer-left {
    padding: 10px;
    box-sizing: border-box;
    border-left: 1px #8E8E8E dotted;
    border-bottom: 1px #8E8E8E dotted;
}

.pailie {
    display: flex;
}

/* .pailie .right {
    background-color: orange;
} */

.designer-right .top {
    margin-left: 25px;
}

.vue-drag-resize {
    border-bottom: 1px #8E8E8E dotted;
    cursor: move;

}

.designer-template {
    padding: 10px;
}

.vue-drag-resize-active {
    outline: 1px dashed #d6d6d6;

}

.vdr.active:before {
    content: "";
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    outline: none;
}

.el-dialog__body {
    padding: 0 !important;
}

.dialog-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
}


:deep(.dialog-def .el-dialog__body) {
    height: calc(100% - 50px) !important;
}
</style>